<?php

namespace app\admin\command;

use app\admin\model\Reserve;
use app\admin\model\Room;
use app\admin\model\Setting;
use app\common\library\Yunding;
use Carbon\Carbon;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;

class ToThirdpartyGeneratePassword extends Command
{

    protected function configure()
    {
        $this->setName('to_thirdparty_generate_password')
            ->setDescription('notice third party to generate password');
    }

    protected function execute(Input $input, Output $output)
    {
        @ini_set("memory_limit",'-1');
        $stime=microtime(true);

        $ReservesInTwoDays = Reserve::with(['room', 'store'])->where('starttime', '<', Carbon::now()->addDays(2)->toDateTimeString())
            ->where('starttime', '>', Carbon::now()->toDateTimeString())
            ->where('yunding_password_id', null)
            ->where('re_status', 1)
            ->select();

        $unlockInAdvanceMin = Setting::getUnlockInadvanceMin();

        $yunding = new Yunding();
        foreach ($ReservesInTwoDays as $reserve) {
            //$phoneNumber = $reserve->store->store_mobile ?? Env::get('common.mobile');
            $phoneNumber = Env::get('common.mobile');

            $startTime = Carbon::parse($reserve->starttime);
            if ($unlockInAdvanceMin > 0) {
                $startTime->subMinutes($unlockInAdvanceMin);
            }

            $password = $yunding->addPassword($reserve->room->yunding_homeid, $reserve->room->yunding_uuid,
                $phoneNumber,
                $startTime->toDateTimeString(),
                $reserve->endtime);

            if ($password) {
                $reserve->opendoor_pwd = $password['password'];
                $reserve->yunding_password_id = $password['password_id'];
                $reserve->yunding_serviceid = $password['serviceid'];
                $reserve->yunding_errno = '1000';
                $reserve->save();
            }
        }

        $etime=microtime(true);//获取程序执行结束的时间
        $total=$etime-$stime;   //计算差值
        $output->writeln($total);
    }

}
